package main.java.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumer02 {
    public static void main(String[] args) {
        Date2 date2 = new Date2();
        new Thread(()->{
            for(int i = 0;i<30;i++){
                try {
                    date2.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for(int i = 0;i<30;i++){
                try {
                    date2.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for(int i = 0;i<30;i++){
                try {
                    date2.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for(int i = 0;i<30;i++){
                try {
                    date2.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

class Date2  {
    private int number = 0;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();


    // +1
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //这里用if会存在虚假唤醒的问题 所以用while
            while (number != 0){
                //等待
                condition1.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"->"+number);
            //通知其他线程
            condition1.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    // -1
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //这里用if会存在虚假唤醒的问题 所以用while
            while (number == 0){
                //等待
                condition1.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"->"+number);
            //通知其他线程
            condition1.signalAll();
            condition1.notifyAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

